import wx
import datetime
from wx.lib.pubsub import setuparg1
from wx.lib.pubsub import pub


import SimplePanels
from ViewBaseChart import ViewBaseChart
from DataManager import DataManager


class ViewTrendChart(ViewBaseChart):
    
    def do_draw(self, data):
        x_tick = data[0]
        x = data[1]
        y = data[2]
        x_lim = data[3]
        #x = [1,2,3,3,4,5,6]
        #y = [1,2,3,4,5,6,7]
        self.axes.plot(x, y, marker='o')
        self.axes.set_xticks(x_tick)
        self.axes.set_xlim(0,x_lim)
        self.axes.set_ylim(0,5)
        
    def get_data(self):
        tm = self.GetParent().time_mode
        if tm == SimplePanels.PANEL_VIEW_TIME_DAY:
            return self.get_data_day()
        elif tm == SimplePanels.PANEL_VIEW_TIME_WEEK:
            return self.get_data_week()
        elif tm == SimplePanels.PANEL_VIEW_TIME_MONTH:
            return self.get_data_month()
        else:
            assert(0)

        
    def get_data_day(self):
        offset = self.DATA_OFFSET
        x_tick = range(0,25)#[0,24]
        xy = []
        for i in DataManager.record.data:
            #y.append(i[offset]) #motion or rating
            #x.append(self.datetime_to_point_hour(i[1], i[2]))
            xy.append((self.datetime_to_point_hour(i[1], i[2]), i[offset]))
        lf = lambda x,y: int(x[0]-y[0])
        xy.sort(lf)
        x = [i[0] for i in xy]
        y = [i[1] for i in xy]

        return (x_tick, x, y, 24)
        
    def get_data_week(self):
        offset = self.DATA_OFFSET
        x_tick = range(1,8)#[1,7]
        x = range(1,8)
        y = [0] * 7
        y_t = [1] * 7 #this disabled divide by zero problem
        for i in DataManager.record.data:
            idx = i[1].weekday()
            delta = (i[2] - i[1]).total_seconds()
            y[idx] += i[offset] * delta
            y_t[idx] += delta

        y = [i/j for i,j in zip(y, y_t)]
        return (x_tick, x, y, 7+1)
        

    def get_data_month(self):
        #NOTE:here(different from calendar), end date is the first day of
        #the next month, so, the 2nd last day got the biggest day number
        end_date = DataManager.record.end - datetime.timedelta(1)
        ed = end_date.day#I don't even know how many days are there
        x_tick = range(1,ed+1)#[1,7]
        x = range(1,ed+1)
        y = [0] * ed
        y_t = [1] * ed #this disabled divide by zero problem
        for i in DataManager.record.data:
            idx = (i[1].day-1)
            delta = (i[2] - i[1]).total_seconds()
            y[idx] += i[self.DATA_OFFSET] * delta
            y_t[idx] += delta

        y = [i/j for i,j in zip(y, y_t)]
        return (x_tick, x, y, ed+1)

    
    @staticmethod
    def datetime_to_point_hour(dt1, dt2):
        return (dt1.hour + dt2.hour)/2 + (dt1.minute+dt2.minute) / 120.0        

class ViewRatingTrendChart(ViewTrendChart):
    DATA_OFFSET = 3

class ViewMoodTrendChart(ViewTrendChart):
    DATA_OFFSET = 4

